﻿ 
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ProjBackEnd.Common;
using ProjBackEnd.Common.Business;
using ProjBackEnd.Common.Helper;
using ProjBackEnd.Models;
using ProjBackEnd.Models.AppModel.AppUserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 

namespace ProjBackEnd.Service
{
    public  sealed partial class AppUserService
    {
        /// <summary>
        /// 获取微信OpenID
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string GetWeChatOpenid(GetWeChatOpenidModel model)
        {
            string conn = Function.GetConnectionString( );

            ResultModel resultObj = new ResultModel();

            //获取银联支付参数

            string sql = $@"select * from CD_BASIC where attrcd IN ('{SystemParaType.WeChatOpenid}','{SystemParaType.WeChapSeceret}')";

            DataSet dsPara = SqlHelper.GetDataSet(sql, conn);
             
            try
            {
                string appid = "";
                if (dsPara.Tables[0].Select($"attrcd = '{SystemParaType.WeChatOpenid}'").Length < 1)
                {
                    throw new Exception("没有配置小程序参数！");
                }
                appid = dsPara.Tables[0].Select($"attrcd = '{SystemParaType.WeChatOpenid}'")[0]["speccn"].ToString().Trim();

         
                string appseceret = "";
                if (dsPara.Tables[0].Select($"attrcd = '{SystemParaType.WeChapSeceret}'").Length < 1)
                {
                    throw new Exception("没有配置小程序参数！");
                }
                appseceret = dsPara.Tables[0].Select($"attrcd = '{SystemParaType.WeChapSeceret}'")[0]["speccn"].ToString().Trim();
                //"7e19a1f2e319e71b5bd9325d1a9fb1b0";
                  
                string grant_type = "authorization_code";
                string jsoncode = model.jscode.Trim();

                string url = $@"https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={appseceret}&js_code={jsoncode}&grant_type={grant_type}";

                string result = HttpHelper.HttpWebRequestGet(url);

            
                GetWeChatOpenidResultModel obj = JsonConvert.DeserializeObject<GetWeChatOpenidResultModel>(result);
                if (string.IsNullOrEmpty(obj.openid))
                {
                    throw new Exception("返回openid失败！");
                }
                 
                resultObj.code = "0";
                resultObj.message = "";
                resultObj.data = obj.openid;
                resultObj.data2 = obj.session_key;

                return JsonConvert.SerializeObject(resultObj);
            }
            catch (Exception ex)
            {
                resultObj.code = "99";
                resultObj.message = ex.Message;
                resultObj.data = "";
                resultObj.data2 = "";
                return JsonConvert.SerializeObject(resultObj);
            }
        }


        /// <summary>
        /// 微信登陆
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string WechatLogin(WechatLoginModel model)
        {
            string conn = Function.GetConnectionString();

            WechatLoginResultModel resultObj = new WechatLoginResultModel();

            try
            {
                if (model == null)
                {
                    throw new Exception("对象为空！");
                }

                if (string.IsNullOrEmpty(model.wxid))
                {
                    throw new Exception("微信标识不能为空！");
                }

                string wxid = model.wxid.Trim();

                string sql = $@"select 
                                    aua.memberid, 
                                    aua.mpno,
                                    aua.password,
                                    aua.username, 
                                    aua.userid, 
                                    aua.nickname,
                                    aua.stat, 
                                    aua.wxid 
                                from SYS_USERTB as aua 
                                where aua.wxid = '{wxid}'             
                                ";

                //获取数据
                DataSet dsInfo = SqlHelper.GetDataSet(sql, conn);


                if (dsInfo.Tables[0].Rows.Count > 0)
                {
                    //判断用户是否禁用了
                    if (dsInfo.Tables[0].Rows[0]["stat"].ToString().Trim() == "F")
                    {
                        throw new Exception("登录失败，该账户已被禁用！");
                    }
                    resultObj.code = "0";
                    resultObj.message = "登录成功";

                    resultObj.userid = dsInfo.Tables[0].Rows[0]["memberid"].ToString().Trim();
                    resultObj.usertp = "S";
                    if (!string.IsNullOrEmpty(dsInfo.Tables[0].Rows[0]["mpno"].ToString().Trim()))
                    {
                        resultObj.phone = dsInfo.Tables[0].Rows[0]["mpno"].ToString().Trim();
                    }
                    else
                    {
                        resultObj.phone = ""; 
                    }

                    if (string.IsNullOrEmpty(dsInfo.Tables[0].Rows[0]["wxid"].ToString().Trim()))
                    {
                        sql = $@"update SYS_USERTB set wxid = '{wxid}'
                                where memberid = '{resultObj.userid}'";
                        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    }
                    resultObj.userid = dsInfo.Tables[0].Rows[0]["memberid"].ToString().Trim();
                    resultObj.usernm = dsInfo.Tables[0].Rows[0]["nickname"].ToString().Trim(); 
                    resultObj.openid = dsInfo.Tables[0].Rows[0]["wxid"].ToString().Trim(); 
                    resultObj.cusname = ""; 
                    resultObj.taxno = ""; 
                    resultObj.address = ""; 
                    resultObj.ybnsr = ""; 
                    resultObj.tele = ""; 
                    resultObj.banknm = ""; 
                    resultObj.bankno = "";
                 
                    sql = $@"select * from SYS_USERLOGIN where memberid = '{resultObj.userid}'";
                    DataSet dsLogin = SqlHelper.GetDataSet(sql, conn);
                    if (dsLogin.Tables[0].Rows.Count < 1)
                    {
                        sql = $@"insert into SYS_USERLOGIN(memberid,logindt,ostp,
                                        deviceid,token,tokenexpire,
                                        platcd,devicebrand) 
                                    values('{resultObj.userid}',getdate(),'',
                                        '','',getdate(),
                                        '','')";
                        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    }
                    else
                    {
                        sql = $@"update SYS_USERLOGIN set logindt = getdate()
                                    where memberid = '{resultObj.userid}'";
                        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    }
                }
                else
                {
                    //不存在
                    throw new Exception("用户不存在！");
                }


                return JsonConvert.SerializeObject(resultObj);
            }
            catch (Exception ex)
            {
                resultObj.code = "99";
                resultObj.message = ex.Message;

                return JsonConvert.SerializeObject(resultObj);
            } 
        }


        /// <summary>
        /// 微信+手机号登陆
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string WechatPhoneLogin(WechatLoginPhoneModel model)
        {
            string data = SimpleCrypt.DecryptData(model.encrytedData,
                 model.sessionKey, model.iv);
            JObject obj = JObject.Parse(data);
            string phoneNumber = obj["phoneNumber"].ToString();

            if (string.IsNullOrEmpty(phoneNumber))
            {
                throw new Exception("手机号为空");
            }

            //连接字符串
            string conn = Function.GetConnectionString();

            WechatLoginResultModel resultObj = new WechatLoginResultModel();

            try
            {
                if (model == null)
                {
                    throw new Exception("对象为空！");
                }

                if (string.IsNullOrEmpty(model.openId))
                {
                    throw new Exception("微信标识不能为空！");
                }

                string wxid = model.openId.Trim();

                string sql = $@"select 
                                    aua.memberid, 
                                    aua.mpno,
                                    aua.password,
                                    aua.username, 
                                    aua.userid, 
                                    aua.nickname,
                                    aua.stat, 
                                    aua.wxid 
                                from SYS_USERTB as aua 
                                where aua.wxid = '{wxid}' or aua.mpno = '{phoneNumber}'            
                                ";

                //获取数据
                DataSet dsInfo = SqlHelper.GetDataSet(sql, conn);


                if (dsInfo.Tables[0].Rows.Count > 0)
                {
                    //判断用户是否禁用了
                    if (dsInfo.Tables[0].Rows[0]["stat"].ToString().Trim() == "F")
                    {
                        throw new Exception("登录失败，该账户已被禁用！");
                    }
                    resultObj.code = "0";
                    resultObj.message = "登录成功";
                     
                    resultObj.userid = dsInfo.Tables[0].Rows[0]["memberid"].ToString().Trim();
                    resultObj.usertp = "S";
                    if (!string.IsNullOrEmpty(dsInfo.Tables[0].Rows[0]["mpno"].ToString().Trim()))
                    {
                        resultObj.phone = dsInfo.Tables[0].Rows[0]["mpno"].ToString().Trim();
                    }
                    else
                    {
                        resultObj.phone = phoneNumber;
                        sql = $@"update SYS_USERTB set phone = {phoneNumber}
                                where memberid = '{resultObj.userid}'";
                        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    }

                    if (string.IsNullOrEmpty(dsInfo.Tables[0].Rows[0]["wxid"].ToString().Trim()))
                    {
                        sql = $@"update SYS_USERTB set wxid = '{wxid}'
                                where memberid = '{resultObj.userid}'";
                        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    }

                    resultObj.usernm = dsInfo.Tables[0].Rows[0]["nickname"].ToString().Trim();
                    //resultObj.trkcd = dsInfo.Tables[0].Rows[0]["trkcd"].ToString().Trim(); 
                    //resultObj.cusref = dsInfo.Tables[0].Rows[0]["cusref"].ToString().Trim(); 
                    resultObj.openid = dsInfo.Tables[0].Rows[0]["wxid"].ToString().Trim();

                    //if (dsInfo.Tables[0].Rows[0]["cusname"].ToString().Trim() != "")
                    resultObj.cusname = "";
                    //else
                    //    resultObj.cusname = dsInfo.Tables[0].Rows[0]["app_user_clientname"].ToString().Trim();

                    //if (dsInfo.Tables[0].Rows[0]["faxno"].ToString().Trim() != "")
                    resultObj.taxno = "";
                    //else
                    //    resultObj.taxno = dsInfo.Tables[0].Rows[0]["app_user_clienttaxno"].ToString().Trim();

                    //if (dsInfo.Tables[0].Rows[0]["address"].ToString().Trim() != "")
                    resultObj.address = "";
                    //else
                    //    resultObj.address = dsInfo.Tables[0].Rows[0]["app_user_clientaddress"].ToString().Trim();

                    //if (dsInfo.Tables[0].Rows[0]["ybnsr"].ToString().Trim() != "")
                    resultObj.ybnsr = "";
                    //else
                    //    resultObj.ybnsr = dsInfo.Tables[0].Rows[0]["app_user_ybnsr"].ToString().Trim();

                    //if (dsInfo.Tables[0].Rows[0]["tel1"].ToString().Trim() != "")
                    resultObj.tele = "";
                    //else
                    //    resultObj.tele = dsInfo.Tables[0].Rows[0]["app_user_clienttele"].ToString().Trim();

                    //if (dsInfo.Tables[0].Rows[0]["RMBBANK"].ToString().Trim() != "")
                    resultObj.banknm = "";
                    //else
                    //    resultObj.banknm = dsInfo.Tables[0].Rows[0]["app_user_clientbank"].ToString().Trim();

                    //if (dsInfo.Tables[0].Rows[0]["RMBACCOUNTNO"].ToString().Trim() != "")
                    resultObj.bankno = "";
                    //else
                    //    resultObj.bankno = dsInfo.Tables[0].Rows[0]["app_user_clientbankno"].ToString().Trim();

                    sql = $@"select * from SYS_USERLOGIN where memberid = '{resultObj.userid}'";
                    DataSet dsLogin = SqlHelper.GetDataSet(sql, conn);
                    if (dsLogin.Tables[0].Rows.Count < 1)
                    {
                        sql = $@"insert into SYS_USERLOGIN(memberid,logindt,ostp,
                                        deviceid,token,tokenexpire,
                                        platcd,devicebrand) 
                                    values('{resultObj.userid}',getdate(),'',
                                        '','',getdate(),
                                        '','')";
                        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    }
                    else
                    {
                        sql = $@"update SYS_USERLOGIN set logindt = getdate()
                                    where memberid = '{resultObj.userid}'";
                        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    }
                }
                else
                {
                    ////不存在

                    //string newuserid = System.Guid.NewGuid().ToString("N");


                    //sql = $@"insert into app_user(userid,passwd,phone,usernm,regdt,idcard,flag,usertp,cusref,wxid)
                    //            values('{newuserid}','123456',{phoneNumber},'',getdate(),'','Y','{AppUserType.Self}','','{wxid}')";
                    //SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);

                    //sql = $@"select * from app_user_loginlog where userid = '{newuserid}'";
                    //DataSet dsLogin = SqlHelper.GetDataSet(sql, conn);
                    //if (dsLogin.Tables[0].Rows.Count < 1)
                    //{
                    //    sql = $@"insert into app_user_loginlog(userid,logdt,logcount) 
                    //            values('{newuserid}',getdate(),1)";
                    //    SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    //}
                    //else
                    //{
                    //    sql = $@"update app_user_loginlog set logcount = isnull(logcount,0) + 1,logdt = getdate()
                    //            where userid = '{newuserid}'";
                    //    SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql);
                    //}

                    //resultObj.code = "0";
                    //resultObj.message = "登录成功";

                    //resultObj.userid = newuserid;
                    //resultObj.usertp = "S";
                    //resultObj.phone = "";
                    //resultObj.usernm = "";
                    //resultObj.trkcd = "";
                    //resultObj.cusname = "";
                    //resultObj.cusref = "";
                    //resultObj.taxno = "";
                    //resultObj.openid = wxid;
                    //resultObj.address = "";
                    //resultObj.ybnsr = "";
                    //resultObj.tele = "";
                    //resultObj.banknm = "";
                    //resultObj.bankno = "";
                    throw new Exception("用户不存在！");
                }


                return JsonConvert.SerializeObject(resultObj);
            }
            catch (Exception ex)
            {
                resultObj.code = "99";
                resultObj.message = ex.Message;

                return JsonConvert.SerializeObject(resultObj);
            }


        }
         
    }
}
